import { reactive } from "vue"

export default () => {
  const state = reactive({
    type: '' as 'add' | 'edit',
    form: null as any,
    action: {
      detail: null,
      add: null,
      edit: null,
    },
  } as any)
  //表单类型
  const defineType = (val: 'add' | 'edit') => {
    state.type = val;
  }
  //表单内容
  const defineForm = (obj: Object) => {
    state.form = obj;
  }
  //表单动作
  const defineAction = (actions: any) => {
    state.action.detail = actions.detail;
    state.action.add = actions.add;
    state.action.edit = actions.edit;
  }
  //表单提交
  const submit = async ({ defineParams, defineSuccess, defineError }) => {
    const params = defineParams?.(state.form) || state.form;
    const res = await state.action?.[state.type]?.(params);
    if (res) {
      defineSuccess(res)
    } else {
      defineError(res)
    }
  }
  return {
    state,
    defineType,
    defineForm,
    defineAction,
    submit,
  }
}